<template>
  <div class="createPost-container">
    <el-form
      ref="postForm"
      :model="postForm"
      class="form-container"
    >
      <div class="createPost-main-container">
        <el-collapse v-model="activeNames">
          <el-collapse-item name="1">
            <template slot="title">
              <i class="header-icon el-icon-info"></i>基础信息
            </template>
            <el-row gutter="80">
              <div class="postInfo-container">
                <el-col :span="12">
                  <el-row>
                    <el-form-item
                      style="margin-bottom: 40px"
                      label-width="180px"
                      label="项目名称:"
                      prop="projectName"
                    >
                      <el-input
                        v-model="postForm.projectName"
                        :maxlength="100"
                        name="name"
                        disabled
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>
                  <el-row>
                    <el-form-item
                      style="margin-bottom: 40px"
                      label-width="180px"
                      label="所属课题组:"
                      prop="projectGroupName"
                    >
                      <el-input
                        v-model="postForm.projectGroupName"
                        :maxlength="100"
                        name="name"
                        disabled
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>
                  <el-row>
                    <el-form-item
                      style="margin-bottom: 40px"
                      prop="projectDepartment"
                      label-width="180px"
                      label="所属部门："
                    >
                      <el-input
                        v-model="postForm.projectDepartment"
                        :maxlength="100"
                        name="name"
                        disabled
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>
                  <el-row>
                    <el-form-item
                      style="margin-bottom: 40px"
                      prop="projectApprovedCost"
                      label-width="180px"
                      label="批准经费："
                    >
                      <el-input
                        v-model="postForm.projectApprovedCost"
                        :maxlength="100"
                        name="name"
                        required
                        disabled
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>
                </el-col>
                <el-col :span="12">
                  <el-row>
                    <el-form-item
                      style="margin-bottom: 40px"
                      prop="projectOwnerName"
                      label-width="180px"
                      label="项目负责人："
                    >
                      <el-input
                        v-model="postForm.projectOwnerName"
                        :maxlength="100"
                        name="name"
                        required
                        disabled
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>
                  <el-row>
                    <el-form-item
                      style="margin-bottom: 40px"
                      prop="projectOwnerEmployeeId"
                      label-width="180px"
                      label="负责人员工编号："
                    >
                      <el-input
                        v-model="postForm.projectOwnerEmployeeId"
                        :maxlength="100"
                        name="name"
                        disabled
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>
                  <el-row>
                    <el-form-item
                      style="margin-bottom: 40px"
                      prop="projectOwnerPhone"
                      label-width="180px"
                      label="负责人电话："
                    >
                      <el-input
                        v-model="postForm.projectOwnerPhone"
                        :maxlength="100"
                        name="name"
                        required
                        disabled
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>

                  <el-row>
                    <el-form-item
                      style="margin-bottom: 40px"
                      prop="projectOwnerEmail"
                      label-width="180px"
                      label="负责人邮箱："
                    >
                      <el-input
                        v-model="postForm.projectOwnerEmail"
                        :maxlength="100"
                        name="name"
                        disabled
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>
                </el-col>
              </div>
            </el-row>
          </el-collapse-item>
          <el-collapse-item name="1">
            <template slot="title">
              <i class="header-icon el-icon-info"></i>开题报告
            </template>
            <el-row>
              <el-row>
                <el-form-item label-width="180px" label="开题报告：">
                  <el-upload
                    class="file-uploader"
                    action="http://localhost:3001/api/projects/upload"
                    :limit="1"
                    :on-preview="handlePreview"
                    :before-remove="beforeRemove"
                    :on-exceed="handleExceed"
                    :on-success="handleSuccess"
                    :file-list="SubjectFileList"
                  >
                    <el-button size="small" type="primary"
                               v-if="checkProjectOwner(postForm.id, postForm.projectApplicantId) && !isView">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip" v-if="checkProjectOwner(postForm.id) && !isView">
                      .docs 文件小于500kb
                    </div>
                  </el-upload>
                </el-form-item>
              </el-row>
            </el-row>
          </el-collapse-item>
        </el-collapse>
        <div class="approve-container" v-if="this.isSubjectCheck">
          <div class="approve-approver-container">
            <div class="approve-type-title">{{ approveType }}:</div>
          </div>
          <div class="approve-divider"></div>
          <div class="approve-action-container">
            <el-row>
              <el-form-item
                style="margin-bottom: 40px"
                prop="researcherHonor"
                label-width="180px"
                label="操作："
              >
                <template>
                  <el-radio
                    v-model="approveStatus"
                    label="通过"
                  >通过</el-radio>
                  <el-radio
                    v-model="approveStatus"
                    label="驳回"
                  >驳回</el-radio>
                </template>
              </el-form-item>
              <el-form-item
                style="margin-bottom: 40px"
                label-width="180px"
                label="意见："
              >
                <el-input
                  v-model="approveComment"
                  type="textarea"
                  class=""
                  :autosize="{ minRows: 4, maxRows: 8 }"
                  placeholder="请输入审批意见"
                />
              </el-form-item>
            </el-row>
            <el-row>
              <el-button
                v-loading="loading"
                style="margin-left: 180px; width: 100px"
                type="success"
                @click="approveForm"
              >
                确认
              </el-button>
              <el-button
                v-loading="loading"
                style="margin-left: 100px; width: 100px"
                type="success"
                @click="$router.push(`/project/approve/list`)"
              >
                返回
              </el-button>
            </el-row>
          </div>
        </div>
      </div>

      <el-button
        v-loading="loading"
        style="margin-left: 230px; width: 100px"
        type="success"
        @click="submitForm"
      >
        保存
      </el-button>
    </el-form>
  </div>
</template>

<script>
import { fetchProjectById, updateProject, updateProjectApprove } from "@/api/project";
import { mapGetters } from "vuex";
import { checkProjectOwner } from '@/utils/permission';
import { generateNewDate } from '@/utils/date';

const defaultForm = {
  projectId: "", // 项目编号
  projectName: "", // 项目名称
  projectDeclareId: null,// 项目申报题目id
  projectDeclareName: "", // 项目申报题目
  projectGroupId: null, // 课题组id
  projectGroupName: "", // 课题组名称
  projectOwnerId: null, // 项目负责人ID
  projectOwnerEmployeeId: "", // 项目负责人编号
  projectOwnerName: "", // 项目负责人名字
  projectOwnerPhone: "", // 项目负责人电话
  projectOwnerEmail: "", // 项目负责人邮箱
  projectDepartment: "", // 项目所属部门
  projectSource: "",
  projectCategory: "",
  projectLevel: "",
  projectDirection: "",
  projectResearchDirection: "",
  projectStatus: "", // 项目状态
  projectDeclareDate: null,
  projectCreatedDate: null,
  projectStartDate: null,
  projectExpectedEndDate: null,
  projectEndDate: null,
  projectApprovedCost: null, // 项目已批准经费
  projectAppliedCost: null,
  projectAppliedCostItems: [],
  projectResultForm: "",
  projectStatisticalYear: null, // 项目统计年度
  projectAttachFileName: "", // 项目立项报告名字
  projectAttachFileUrl: "", // 项目立项报告地址
  projectChangeReport: "", // 项目变更证明材料
  projectChangeReportName: "", // 项目变更证明材料名称
  projectChangeDescription: "", // 项目变更说明
  projectEthicalApproverId1: null,
  projectEthicalApproverName1: "",
  projectEthicalApproverId2: null,
  projectEthicalApproverName2: "",
  projectCostApproverId: null,
  projectCostApproverName: "",
  projectPreApproverId: null,
  projectPreApproverName: "",
  projectEndApproverId: null,
  projectEndApproverName: "",
  projectApplicantId: null,
  projectApplicantName: "",
  projectInformationCheckStatus: "", // 项目信息审核状态
  projectInformationCheckHistory: null,
  projectSubjectReport: "", // 项目中检报告
  projectSubjectReportName: '', // 项目中检文件名
  projectSubjectDate: null, // 项目中检日期
  projectSubjectDescription: "", // 项目中检说明
  projectSubjectApproverId: null, // 项目中检者ID
  projectSubjectApproverName: "", // 项目中检者名字
  projectMidReportName: "", // 项目中检文件名
  projectMidReport: "", // 项目中检报告
  projectMidDate: null, // 项目中检日期
  projectMidDescription: "", // 项目中检说明
  projectFinalReportName: "", // 项目结项文件名
  projectFinalReport: "", // 项目结项报告
  projectFinalDate: null, // 项目结项日期
  projectFinalDescription: "", // 项目结项说明
  projectMidApproverId: null, // 项目中检者ID
  projectMidApproverName: "", // 项目中检者名字
  projectFinalApproverId: null, // 项目结项者ID
  projectFinalApproverName: "", // 项目结项者名字
  projectCheckStatus: "提交项目中检报告", // 项目审批状态
  projectCheckHistory: null, // 项目审批履历
  projectChangeHistory: null,
  projectChangeStatus: null, // 项目变更状态
  projectEthicCheckCount: 0, // 伦理审批通过个数
  action: "",
  id: undefined,
};

export default {
  name: "ProjectCheckDetail",
  props: {
    isView: {
      type: Boolean,
      default: false,
    },
    isSubjectCheck: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      approveType: "", // 中检审批，结项审批
      approveStatus: "通过",
      approveComment: "",
      activeNames: ["1"],
      SubjectFileList: [],
      finalFileList: [],
    };
  },
  computed: {
    ...mapGetters(["id", "name", "roles"]),
  },
  created() {
    const id = this.$route.params && this.$route.params.id;
    if (this.isMid) {
      this.approveType = "中检审批";
    } else if (this.isEnd) {
      this.approveType = "结项审批";
    }
    this.fetchData(id);
  },
  methods: {
    checkProjectOwner,
    handlePreview(file) {
      let a = document.createElement('a');
      let event = new MouseEvent('click');
      a.download = file.name;
      a.href = file.response? `http://localhost:3001/${file.response.srcurl}` : file.url;
      a.dispatchEvent(event);
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `文件数量限制为1, 您选择了 ${files.length} 个文件。`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`删除 ${file.name} ?`);
    },
    async handleSuccess(res, file) {
      if (res.status === "1") return this.$message.error(res.message);
      this.postForm.projectSubjectReport = `http://localhost:3001/${res.srcurl}`;
      this.postForm.projectSubjectReportName = file.name;
    },
    fetchData(id) {
      fetchProjectById(id)
        .then((res) => {
          this.postForm = res.data[0];
          this.SubjectFileList = this.postForm.projectSubjectReportName
            ? (this.SubjectFileList = [
              {
                name: this.postForm.projectSubjectReportName,
                url: this.postForm.projectSubjectReport,
              },
            ])
            : [];
        })
        .catch((err) => {
          console.log(err);
        });
    },
    submitForm() {
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.postForm.action = "subjectReport";
          this.postForm.projectCheckStatus = '提交项目中检报告'
          updateProject(this.postForm.id, this.postForm)
            .then((res) => {
              if (res.data) {
                this.$router.push("/project/subject/list");
                this.$message({
                  title: "成功",
                  message: "项目开题信息更新成功",
                  type: "success",
                  duration: 2000,
                });
              } else {
                this.$message({
                  message: "项目中检信息更新失败",
                  type: "error",
                });
              }
              this.loading = false;
            })
            .catch((err) => {
              this.loading = false;
            });
        } else {
          console.log("项目开题信息更新失败");
          return false;
        }
      });
    },
    approveForm() {
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          this.loading = true;

          if (this.isSubjectCheck) {
            if (this.approveStatus === "通过") {
              this.postForm.projectCheckStatus = "提交项目中检报告";
            } else {
              this.postForm.projectCheckStatus = "项目开题报告审批驳回";
            }
            this.postForm.projectSubjectDate = generateNewDate();
            this.postForm.projectSubjectDescription = this.approveComment;
            this.postForm.projectSubjectApproverId = this.id;
            this.postForm.projectSubjectApproverName = this.name;
          }
          updateProjectApprove(this.postForm.id,
            {projectForm: this.postForm, changeForm: null,
              isChange: false, isMemberChange: false}) // need to add
            .then((res) => {
              if (res.data) {
                this.$router.push("/project/approve/list");
                this.$message({
                  title: "成功",
                  message: "审批信息保成功",
                  type: "success",
                  duration: 2000,
                });
              } else {
                this.$message({
                  message: "审批信息保存失败",
                  type: "error",
                });
              }
              this.loading = false;
            })
            .catch((err) => {
              this.loading = false;
            });
        } else {
          console.log("审批信息保存失败");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }
}

.identity-container {
  margin-top: 50px;
}

.approve-container {
  border: 1px solid #ebebeb;
  border-radius: 3px;

  .approve-approver-container {
    padding: 16px 0 16px 5px;
  }

  .approve-action-container {
    padding-bottom: 16px;;
  }

  .approve-divider {
    background-color: #fafafa;
    border-top: 1px solid #eaeefb;
    overflow: hidden;
    height: 0;
  }
}
</style>
